package jmine.tec.script.persistent.api;

import jmine.tec.script.ScriptDispatcher;
import jmine.tec.script.ScriptExecutionContext;
import jmine.tec.script.persistent.domain.Script;
import jmine.tec.script.persistent.domain.ScriptPurpose;
import bancosys.tec.persist.controller.PersistenceEnabledController;
import bancosys.tec.persist.dao.BaseDAO;

/**
 * Testador de scripts de API
 * 
 * @author lundberg
 */
public class ApiScriptTester {

    private PersistenceEnabledController controller;

    private ScriptDispatcher dispatcher;

    /**
     * @param controller
     */
    public ApiScriptTester(PersistenceEnabledController controller, ScriptDispatcher dispatcher) {
        this.controller = controller;
        this.dispatcher = dispatcher;
    }

    /**
     * Testa a api com o mnemônico dado
     * 
     * @param mneApi mneApi
     * @param paramVariable paramVariable
     * @param param param
     * @param body body
     * @throws Throwable Throwable
     */
    public void run(String mneApi, final String paramVariable, final Object param, String body) throws Throwable {
        BaseDAO<Script> dao = this.controller.getDAOFactory().getGenericDAO(Script.class);
        BaseDAO<ScriptPurpose> purposeDAO = this.controller.getDAOFactory().getGenericDAO(ScriptPurpose.class);
        Script api = dao.findByNaturalKey(mneApi);
        ScriptPurpose purpose = purposeDAO.createBean();
        purpose.setExecutionContext(ApiTestScriptExecutionContext.class.getCanonicalName());
        Script script = dao.createBean();
        script.setBody(body);
        script.setLanguage(api.getLanguage());
        script.getApis().add(api);
        script.setPurpose(purpose);
        ScriptExecutionContext<Void> context = script.createContext(ApiTestScriptExecutionContext.class).prepare(paramVariable, param);
        this.dispatcher.dispatchExecution(context);
    }
}
